/*
	Add Internet Explorer render tags to output
	
	Version 20110531
	
	http://www.wvanweelden.eu/robohelp/scripts/ierendertags
	
	This script is licenced under a CC Attribution-Share Alike 3.0 Unported license: http://creativecommons.org/licenses/by-sa/3.0/
*/

//Supported SSL
var WebHelp = RoboHelp.SSLLayoutType.WEBHELP;
var WebHelpPro = RoboHelp.SSLLayoutType.WEBHELPPRO;
var FlashHelp = RoboHelp.SSLLayoutType.FLASHHELP;
var FlashHelpPro = RoboHelp.SSLLayoutType.FLASHHELPPRO;
var XML = RoboHelp.SSLLayoutType.XMLOUTPUT;
var SupportedSSL = new Array(WebHelp, WebHelpPro, FlashHelp, FlashHelpPro, XML);

//Render settings + descriptions
var EDGE = "edge";
var EDGETXT = "Newest mode possible";
var IE9 = "9";
var IE9TXT = "IE9 mode";
var IE8 = "8";
var IE8TXT = "IE8 mode";
var IE7 = "7";
var IE7TXT = "IE7 mode";
var IE55 = "5.5";
var IE55TXT = "IE5.5 mode";
var RenderModeText = new Array(EDGETXT, IE9TXT, IE8TXT, IE7TXT, IE55TXT);


//Available topic types
var FM = "FrameMaker topics (linked and imported)";
var All = "All topics";
var TopicChooser = new Array(All, FM);

//Chosen values
var chosenSSL;
var chosenRender;
var chosenTopics;

//Output folder
var outputfolder;

//Dialog resources
var dlg;
var dialogresource = "dialog {  \
	text:'Choose output format and IE rendering mode',  \
	alignChildren: 'right', \
	sslgroup:Group{  \
		st:StaticText { \
			text: 'Choose output', \
		}, \
		ssl:DropDownList {\
			alignment: ['fill', 'center'], \
			size: ['250','10'], \
		}, \
	},  \
	rendergroup:Group { \
		st:StaticText {\
			text:'Choose rendering mode for Internet Explorer', \
		}, \
		render:DropDownList{ \
			alignment: ['fill', 'center'], \
			size: ['250','10'], \
		}, \
	}, \
	rendertopics:Group {  \
		st:StaticText {  \
			text:'Apply rendering mode to these topics:',  \
		},  \
		topics:DropDownList{ \
			alignment: ['fill', 'center'], \
			size: ['250','10'], \
		}, \
	},  \
	btn:Group { \
		go:Button { \
			text:'Execute', \
		}, \
		cancel:Button { \
			text:'Cancel', \
		}, \
	}, \
}";

start();
function start()
{
	if(typeof(RoboHelp) == "undefined")
		alert("Please start RoboHelp and open a project to use this script");
	else if(typeof(RoboHelp.project) == "undefined")
		alert("Please open a project to use this script");
	else
		showdialog();
}
function showdialog()//Show dialog
{
	dlg = new Window(dialogresource);
	var hasSSL = addSSL();
	if(!hasSSL)
	{
		alert("There are no layouts to compile. Stopping script");
		return false;
	}
	addRenderMode();
	addTopicSelector();
	dlg.btn.go.onClick = CheckInput;
	dlg.show();
}
function addSSL() {//Add supported ssl to dialoges
	var added = false;
	var sslmngr = RoboHelp.project.SSLManager;
	for(var i = 1; i<=sslmngr.count; i++)
	{
		var ssl = sslmngr.item(i);
		if(in_array(ssl.layoutType, SupportedSSL))
		{
			dlg.sslgroup.ssl.add("item", ssl.name);
			added = true;
		}
	}
	return added;
}
function addRenderMode()
{
	for(var i = 0; i<RenderModeText.length;i++)
	{
		dlg.rendergroup.render.add("item", RenderModeText[i]);
	}
}
function addTopicSelector()
{
	for(var i = 0; i<TopicChooser.length; i++)
	{
		dlg.rendertopics.topics.add("item", TopicChooser[i]);
	}
}
function in_array(value, array)
{
	var inarray = false;
	for(var i = 0; i<array.length;i++)
	{
		if(value == array[i])
		{
			inarray = true;
			break;
		}
	}
	return inarray;
}
function CheckInput()//check user input
{
	var inputok = true;
	if(isValidType(dlg.sslgroup.ssl.selection))
		chosenSSL = dlg.sslgroup.ssl.selection.toString();
	else
		inputok = false;
		
	if(isValidType(dlg.rendergroup.render.selection))
		chosenRender = dlg.rendergroup.render.selection.toString();
	else
		inputok = false;
		
	if(isValidType(dlg.rendertopics.topics.selection))
		chosenTopics = dlg.rendertopics.topics.selection.toString();
	else
		inputok = false;
	
	if(inputok)
		Execute();
	else
		alert("Please select an SSL, a render mode and the topics  to process.");
}
function isValidType(value) {
    if (typeof (value) !== 'undefined' && value != null) {
        return true;
    }
    return false;
}
function Execute()//Compile layout and modify files
{
	dlg.hide();
    msg("\n\n");
	if(GenerateOutput())
	{
		updateFiles();
		alert("Script execution finished");
	}
	else
		alert("There was an error while generating SSL. Script execution stopped.");
}
function GenerateOutput()//Generate SSL
{
    msg("Generating output\n");
	var outputssl = false;
	var sslmngr = RoboHelp.project.SSLManager;
	for(var i = 1; i<=sslmngr.count; i++)
	{
		var ssl = sslmngr.item(i);
		if(ssl.name == chosenSSL)
		{
			outputssl = ssl;
			break;
		}
	}
	if(ssl === false)
		return false;
	else
	{
		outputssl.generate();
		var sslOutputFileName = new File(ssl.outputFileName);
		outputfolder = sslOutputFileName.parent;
		
		return true;
	}
}
function updateFiles()//Update all files
{
	var RenderString = GetRenderString();
		var outputfiles = LoadFiles(outputfolder);
	for(var i = 0; i<outputfiles.length; i++)
	{
		var filetxt = readFile(outputfiles[i]);
		var procestopic = true;
		if(chosenTopics != All)
		{
			if(chosenTopics == FM)
				procestopic = FMOriginated(filetxt);
		}
	
		if(procestopic)
		{
            msg("Updating file "+outputfiles[i]+"\n");
			filetxt = filetxt.replace("<head>", "<head>"+RenderString);
			writeToFile(outputfiles[i], filetxt, true);
		}
	}
}
function LoadFiles(folder)//Get all output files recursively
{
	var editfiles = new Array();
	var files = folder.getFiles("*.*");
	for(var i = 0; i<files.length; i++)
	{
		var tempfile = files[i];
		 if (tempfile instanceof Folder) {/* Load folder recursive */
			 var folder = new Folder(tempfile);
			 var temparray = LoadFiles(folder);
			 editfiles = editfiles.concat(temparray);
		 }
		else if(tempfile instanceof File) {
			var neededextension = ".htm";
			var extension = FileExtension(tempfile.fsName.toLowerCase());
			if(extension == neededextension)
				editfiles.push(tempfile.fsName);
		}
	}
	return editfiles;
}
function FileExtension(filename) {
   var strExtension="";
    var index = filename.lastIndexOf(".");
    if (index != -1) {
        strExtension = filename.substr(index, filename.length - index);
        strExtension = strExtension.toLowerCase();
    }
    return strExtension;
}
function GetRenderString()
{
	var render;
	switch (chosenRender) {
		case EDGETXT:
			render = EDGE;
			break;
		case IE9TXT:
			render = IE9;
			break;
		case IE8TXT:
			render = IE8;
			break;
		case IE7TXT:
			render = IE7;
			break;
		case IE55TXT:
			render=IE55;
			break;
	}
	return '<meta http-equiv="X-UA-Compatible" content="IE='+render+'" />';
}
function readFile(szFilePath) {
	//if it is RH9 then we will use the readWholeFile function
	if (IsRoboHelp9OrLater())
		return RoboHelp.readWholeFile(szFilePath); //this takes care of BOM, encoding and all
    else
	{
		var szRetVal = "";
		var fileObj = new File(szFilePath);
		fileObj.open("r");
		while (!fileObj.eof) {
			szRetVal += fileObj.readln();
		}
		fileObj.close();
		return szRetVal;
	}
}
function writeToFile(szFilePath, szOutput, bWriteUsingNewFunction) {
	var bSuccess = false;
	if (bWriteUsingNewFunction && IsRoboHelp9OrLater())
	{
		bSuccess = RoboHelp.writeWholeFile(szFilePath, szOutput); //this takes care of BOM and encoding as well.
	}

	if (!bSuccess)
	{
		var fileObj = new File(szFilePath);
		fileObj.open("w");
		fileObj.write(szOutput);
		fileObj.close();      
	}
}
function IsRoboHelp9OrLater() {
    //get the RoboHelp version
    var versionString = RoboHelp.version;
    var iVersion = parseInt(versionString);
    return (iVersion >= 9);
}
function FMOriginated(filecontents)//Check if it is an FM originated file
{
    var FMString = '<meta name="Originator" content="ImportMif">';
    if(filecontents.indexOf(FMString) != -1)
        return true;
    else
        return false;
}
function msg(message)
{
    RoboHelp.project.outputMessage(message);
}